package com.jingbian.cppccbackend.controller.admin;

import com.jingbian.cppccbackend.entity.ActivityOutcomes;
import com.jingbian.cppccbackend.entity.Result;
import com.jingbian.cppccbackend.service.admin.ActivityOutcomesService;
import com.jingbian.cppccbackend.utils.ResultUtil;
import com.jingbian.cppccbackend.entity.vo.PageVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * <p>
 * 活动成果表 前端控制器
 * </p>
 *
 * @author yezi
 * @since 2025-02-14
 */
@Slf4j
@RestController
@RequestMapping("/admins/activityOutcomes")
public class adminActivityOutcomesController {

    @Autowired
    private ActivityOutcomesService activityOutcomesService;

    //获取活动成果数据
    @GetMapping("/getOutcomes")
    public Result<PageVO<ActivityOutcomes>> getNews(
            Integer pageNum,
            Integer pageSize,
            @RequestParam(required = false,defaultValue = "asc") String sortType,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false) String searchText
    ) {
        PageVO<ActivityOutcomes> outcomes = activityOutcomesService.getOutcomes(
                pageNum, pageSize, sortType, startDate,endDate,searchText);
        return ResultUtil.success(outcomes);
    }

    // 删除活动成果
    @DeleteMapping("/delete/{oid}")
    public Result<String> deleteOutcome(@PathVariable Integer oid) {
        boolean success = activityOutcomesService.deleteOutcome(oid);
        if (success) {
            return ResultUtil.success("删除成功");
        } else {
            return ResultUtil.fail("删除失败");
        }
    }

    // 根据ID获取活动成果详情
    @GetMapping("/getOutcome/{oid}")
    public Result<ActivityOutcomes> getOutcomeById(@PathVariable Integer oid) {
        ActivityOutcomes outcome = activityOutcomesService.getOutcomeById(oid);
        if (outcome != null) {
            return ResultUtil.success(outcome);
        } else {
            return ResultUtil.fail("未找到该活动成果");
        }
    }

    //导出活动成果数据
    @GetMapping("/exportOutcomes")
    public ResponseEntity<byte[]> exportOutcomes(
            @RequestParam(required = false,defaultValue = "asc") String sortType,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false) String searchText) throws IOException {
        log.info("开始导出活动成果列表Excel，参数：sortType={}, startDate={}, endDate={}, searchText={}",
                sortType, startDate, endDate,  searchText);
        log.info("开始导出活动成果列表Excel");

        try {
            // 获取活动成果列表数据
            List<ActivityOutcomes> activityOutcomesList = activityOutcomesService.getOutcomesForExport(sortType, startDate,endDate,searchText);
            System.out.println("活动数据"+activityOutcomesList);
            log.info("获取到 {} 条数据", activityOutcomesList.size());

            // 创建工作簿
            try (XSSFWorkbook workbook = new XSSFWorkbook()) {
                Sheet sheet = workbook.createSheet("活动成果列表");

                // 设置表头样式
                CellStyle headerStyle = workbook.createCellStyle();
                headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
                headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                Font headerFont = workbook.createFont();
                headerFont.setBold(true);
                headerStyle.setFont(headerFont);

                // 创建表头
                Row headerRow = sheet.createRow(0);
                String[] header = {"成果名称",  "摘要", "作者", "活动介绍",  "活动发布时间"};

                for (int i = 0; i < header.length; i++) {
                    Cell cell = headerRow.createCell(i);
                    cell.setCellValue(header[i]);
                    cell.setCellStyle(headerStyle);
                    sheet.autoSizeColumn(i);
                }

                // 填充数据
                int rowNum = 1;
                for (ActivityOutcomes activityOutcomes : activityOutcomesList) {
                    Row row = sheet.createRow(rowNum++);
                    row.createCell(0).setCellValue(activityOutcomes.getTitle());
                    row.createCell(1).setCellValue(activityOutcomes.getSummary());
                    row.createCell(2).setCellValue(activityOutcomes.getAuthor());
                    row.createCell(3).setCellValue(activityOutcomes.getIntroduction());

                    // 设置时间
                    Cell startTimeCell = row.createCell(4);
                    startTimeCell.setCellValue(activityOutcomes.getCreatedAt());
                    CellStyle dateStyle = workbook.createCellStyle();
                    dateStyle.setDataFormat(workbook.createDataFormat().getFormat("yyyy-mm-dd hh:mm:ss"));
                    startTimeCell.setCellStyle(dateStyle);
                }

                // 写入字节数组
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                workbook.write(outputStream);
                byte[] content = outputStream.toByteArray();

                // 设置响应头
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
                String filename = URLEncoder.encode("活动成果列表.xlsx", StandardCharsets.UTF_8).replaceAll("\\+", "%20");
                headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + filename);

                log.info("Excel文件生成成功，大小: {} bytes", content.length);
                return new ResponseEntity<>(content, headers, HttpStatus.OK);
            }
        } catch (Exception e) {
            log.error("导出Excel失败", e);
            throw new RuntimeException("导出Excel失败: " + e.getMessage());
        }
    }


}
